再一次,javascript设计模式与开发实践-状态模式

简述

允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。

酒店的台灯开关顺序通常是:关灯 → 弱等 → 强灯 → 关灯,这这种行为就是状态。

使用场景

  • 文件状态
  • 角色动作
  • ..

案例

如上台灯的状态行为,用多层if可以很快的编写代码,但假如新设计的台灯又多了一种状态呢?
随着情况越来越多,显然if的方式会违反开发-封闭原则,后续维护将变得复杂。
状态模式能够很好的解决这种问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var Light = function () {
this.currState = FSM.off;
this.button = null;
};

Light.prototype.init = function () {
var button = document.createElement('button'),
that = this;

this.button = document.body.appendChild(button);
this.button.onclick = function () {
that.currState.buttonWasPressed.call(that);
};

FSM.off.buttonWasPressed.call(this);
};

var FSM = {
off: {
buttonWasPressed: function () {
console.log('关灯');

this.button.innerHTML = '下一次按我是开灯';
this.currState = FSM.on;
}
},

on: {
buttonWasPressed: function () {
console.log('开灯');

this.button.innerHTML = '下一次按我是关灯';
this.currState = FSM.off;
}
}
};

var light = new Light();
light.init();